using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.HttpLogging;
using Microsoft.EntityFrameworkCore;
using System.Reflection;
using YzApi;

var builder = WebApplication.CreateBuilder(args);

builder.Logging.ClearProviders();
//builder.Logging.AddEventLog();
builder.Logging.AddLog4Net("log4net.config");

//builder.Configuration.GetSection("Wechat").Bind(Helper.Config);


// Add services to the container.
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      policy =>
                      {
#if DEBUG
                          policy.WithOrigins().AllowAnyOrigin()
#else
                          policy.WithOrigins(builder.Configuration.GetValue<string>("cors"))
#endif
                            .AllowAnyMethod();
                      });
});

builder.Services.AddW3CLogging(logging =>
{
    // Log all W3C fields
    logging.LoggingFields = W3CLoggingFields.All;

    logging.FileSizeLimit = 5 * 1024 * 1024;
    logging.RetainedFileCountLimit = 2;
    logging.FileName = "MyLogFile";
    logging.LogDirectory = builder.Configuration.GetValue<string>("w3clog");
    logging.FlushInterval = TimeSpan.FromSeconds(2);
});


builder.Services.AddControllers(opt =>
{
//    opt.Filters.Add(typeof(DbCommitFilter));
//#if DEBUG
//    opt.Filters.Add(typeof(ExceptionFilter));
//#endif
});

builder.Services.AddScoped<DbContext, MysqlDbContext>();

/// <summary>
/// 解决POST时Form表单过长无法读取的问题
/// </summary>
builder.Services.Configure<FormOptions>(opt =>
{
    opt.ValueLengthLimit = int.MaxValue;
    opt.MultipartBodyLengthLimit = int.MaxValue;
    opt.MultipartHeadersLengthLimit = int.MaxValue;

});

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseW3CLogging();

app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
    app.UseSwagger();
    app.UseSwaggerUI();
//}

app.UseAuthorization();

app.MapControllers();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers()
             .RequireCors(MyAllowSpecificOrigins);
});

app.Run();
